package priv.abadstring.study.haoke.im.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import priv.abadstring.study.haoke.im.bean.Message;
import priv.abadstring.study.haoke.im.bean.User;
import priv.abadstring.study.haoke.im.mock.UserMockData;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * UserController
 *
 * @author aBadString
 * @date 2021-07-30 19:23:17
 */
@RestController
@CrossOrigin
public class UserController {
    @Autowired
    private MessageController messageController;
    /**
     * 获取用户列表
     */
    @GetMapping("user")
    public List<Map<String, Object>> queryUserList(@RequestParam("fromId") Long fromId) {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<Long, User> userEntry : UserMockData.USER_MAP.entrySet()) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", userEntry.getValue().getId());
            map.put("avatar", "https://portrait.gitee.com/uploads/avatars/user/2488/7465522_abadstring_1589358352.png!avatar60");
            map.put("from_user", fromId);
            map.put("info_type", null);
            map.put("to_user", map.get("id"));
            map.put("username", userEntry.getValue().getUsername());
            // 获取最后一条消息
            List<Message> messages = messageController.queryMessageList(fromId, userEntry.getValue().getId(), 1, 1);
            if (messages != null && !messages.isEmpty()) {
                Message message = messages.get(0);
                map.put("chat_msg", message.getMsg());
                map.put("chat_time", message.getSendDate().getTime());
            }
            result.add(map);
        }
        return result;
    }
}
